<template>
	<view class="main">
		<u-navbar title-color="#717171" :background="{ backgroundColor: '#ffffff' }" :back-text-style="{color: '#fff'}"
		 :title="tabCurrentIndex==0?$t('recordlist.MusicStore'):tabCurrentIndex==1?$t('recordlist.NewsStore'):tabCurrentIndex==2?$t('recordlist.historyList'):$t('recordlist.followList')">
			<view class="navbar-right" slot="right">
				<view class="message-box right-item" v-show="tabCurrentIndex!=3">
					<text v-show="!delnews" @click="delNewsClick(0)" style="color: #ed4141;margin-right: 25rpx;">{{$t('recordlist.delete')}}</text>
					<text v-show="delnews" @click="delNewsClick(1)" style="color: #bfbfbf;margin-right: 25rpx;">{{$t('detailss.cancel')}}</text>
				</view>
			</view>
		</u-navbar>
		<!-- 顶部选项卡 -->
		<view class="tab-frame">
			<scroll-view id="nav-bar" class="nav-bar" scroll-x scroll-with-animation :scroll-left="scrollLeft">
				<view v-for="(item,index) in tabBars" :key="item.channelId" class="nav-item" :class="{current: index === tabCurrentIndex}"
				 :id="'tab'+index" @click="changeTab(index,item.channelId)">{{item.channelName}}</view>
			</scroll-view>
		</view>
		<!-- 下拉刷新组件 -->
		<mix-pulldown-refresh ref="mixPulldownRefresh" class="panel-content" :top="235" @refresh="onPulldownReresh"
		 @setEnableScroll="setEnableScroll">
			<!-- 内容部分 -->
			<swiper id="swiper" class="swiper-box" :duration="300" :current="tabCurrentIndex" @change="changeTab">
				<swiper-item v-for="(tabItem,index) in tabBars" :key="index">
					<scroll-view class="panel-scroll-box" :scroll-y="enableScroll" @scrolltolower="loadMore">
						<u-empty v-if="tabItem.newsList.length==0" :text="$t('recordlist.recordtet')" mode="favor"></u-empty>
						<!-- 音乐收藏 -->
						<view v-if="index==0" class="video-frame">
							<u-checkbox-group active-color="#f50606" @change="checkboxGroupChange">
								<view class="music-concen" v-for="(item, i) in tabItem.newsList" :key="i">
									<view @click="navToDetails(item,i,index)" :class="['music-img', item.show==true?'img01':'']">
										<image :src="'https://music-asean.oss-cn-hongkong.aliyuncs.com'+item.cover" mode=""></image>
									</view>
									<view @click="navToDetails(item,i,index)" class="music-text">
										<view class="txt">{{item.title}}</view>
										<view>{{item.singer}}</view>
									</view>
									<view class="music-button">
										<!-- <button @click="delClick(item.music_id,2)" v-show="item.show==true" size="mini" type="default">删除</button> -->
										<u-checkbox v-show="item.disabled" icon-size="40" size="40" :name="item.music_id" v-model="item.checked"></u-checkbox>
										<text v-show="item.show==false">{{item.duration}}</text>
									</view>
								</view>
							</u-checkbox-group>
						</view>
						<!-- 新闻收藏/历史记录 -->
						<view v-if="index==1||index==2" class="shortNews">
							<u-checkbox-group active-color="#f50606" @change="checkboxGroupChange">
								<view class="rec-section" v-for="item in tabItem.newsList" :key="item.id">
									<view class="introduce">
										<view class="introduce_img">
											<!-- <image v-if="detailData.media_user.avatar_url"  :src="'http://pic-asean2.oss-cn-hongkong.aliyuncs.com/'+detailData.media_user.avatar_url"  mode=""></image> -->
											<image src="https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1575568780,3963509117&fm=15&gp=0.jpg"
											 mode=""></image>
										</view>
										<view class="introduce_tltle">
											<view>{{item.media_user.name}}</view>
											<text>{{$i18n.locale=='en'?utils.timeTodate('m-d H:i', item.publish_time):utils.friendlyDate(item.publish_time) }}</text>
										</view>
										<u-checkbox v-show="item.disabled" icon-size="40" size="40" :name="item.news_id" v-model="item.checked"></u-checkbox>
									</view>
									<view class="rec-item">
										<view class="left">
											<text @click="navTonews(item.news_id)" class="title">{{item.title}}</text>
											<view class="bot">
												<text class="author">{{item.copy_from}}</text>
												<text class="time">{{ utils.friendlyDate(item.join_time) }}</text>
												<!-- <text v-if="index==1" @click="delClick(item.news_id,1)" class="del">×</text> -->
											</view>
										</view>
										<view @click="navTonews(item.news_id)" class="right" v-if="item.cover.length > 0">
											<image :src="'http://pic-asean2.oss-cn-hongkong.aliyuncs.com/'+item.cover[0].url" class="img" mode="aspectFill"></image>
										</view>
									</view>
								</view>
							</u-checkbox-group>
						</view>
						<!-- 关注 -->
						<view v-if="index==3" class="interview">
							<view class="interview-content" v-for="(item, i) in tabItem.newsList" :key="i">
								<view class="content-info">
									<view class="frame_img">
										<image v-if="item.avatar_url" :src="item.avatar_url" mode=""></image>
										<image v-if="!item.avatar_url" src="https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1575568780,3963509117&fm=15&gp=0.jpg"
										 mode=""></image>
									</view>
									<text>{{item.name}}</text>
								</view>
								<view @click="followClock(item)" style="color: #ed4141;">{{item.falis==true?$t('video.Nofollow'):$t('video.follow')}}</view>
							</view>
						</view>
						<!-- 上滑加载更多组件 -->
						<mix-load-more :status="tabItem.loadMoreStatus"></mix-load-more>
					</scroll-view>
				</swiper-item>
			</swiper>
		</mix-pulldown-refresh>
		<view class="batchDel" v-show="delnews" @click="batchClick">
			<u-icon name="trash" color="#ff0000" size="40"></u-icon>{{$t('recordlist.Batchdel')}}({{delList.length}})
		</view>
		<u-toast ref="uToast" />
	</view>
	</view>
</template>

<script>
	import utils from '@/components/shoyu-date/utils.filter.js';
	import mixAdvert from '@/components/mix-advert/vue/mix-advert';
	import mixPulldownRefresh from '@/components/mix-pulldown-refresh/mix-pulldown-refresh';
	import mixLoadMore from '@/components/mix-load-more/mix-load-more';
	import {
		getLanguage
	} from '@/util/tokeCookien.js'
	let windowWidth = 0,
		scrollTimer = false,
		tabBar;
	export default {
		components: {
			mixPulldownRefresh,
			mixLoadMore,
			mixAdvert
		},
		data() {
			return {
				delList: [], //删除数组
				delnews: false, //多选删除
				listChannel: false, //底部侧频道列表展示
				utils: utils, //时间转换
				tabCurrentIndex: 1, //当前选项卡索引
				scrollLeft: 0, //顶部选项卡左滑距离
				enableScroll: true,
				tabBars: [],
				innerAudioContext: '', //播放函数
				page_index: 1 //当前页数
			}
		},
		onShow() {
			// 获取屏幕宽度
			windowWidth = uni.getSystemInfoSync().windowWidth;
			this.loadTabbars();
		},
		onLoad(options) {
			var id= options.tabindex
			this.tabCurrentIndex = Number(id)
		},
		onBackPress() {
			if (this.innerAudioContext) this.innerAudioContext.destroy()
		},
		methods: {
			//批量删除
			async batchClick() {

					var list_URL = ''
					var type = ''
					if (this.tabCurrentIndex == 2) {
						list_URL = '/user/delete-history-list'
					} else {
						list_URL = '/user/delete-favorite-list'
						this.tabCurrentIndex == 0 ? type = 2 : type = 1
					}
					const res = await this.$myRequest({
						url: list_URL,
						method: 'post',
						header: {},
						data: {
							list: this.delList.join("|"),
							type: type
						}
					})
					console.log(res) 
					if(res.code==200){
					this.$refs.uToast.show({
						title: this.$i18n.messages[this.$i18n.locale].pressrelease.delok,
						type: 'success'
					})
					var tabBar=[]
					var ids=''
					if(this.tabCurrentIndex==0){
						for (let item of this.tabBars[this.tabCurrentIndex].newsList) {
							item.disabled=false
							item.checked=false
								if(!this.in_array(item.music_id, this.delList)){
									tabBar.push(item)
								}
						}
					}else{
						for (let item of this.tabBars[this.tabCurrentIndex].newsList) {
							item.disabled=false
							item.checked=false
								if(!this.in_array(item.news_id, this.delList)){
									tabBar.push(item)
								}
						}
					}
					this.tabBars[this.tabCurrentIndex].newsList=tabBar
					this.delnews=false
				}
			},
			//遍历数组
			in_array(search, array) {
				for (var i in array) {
					if (array[i] == search) {
						return true;
					}
				}
				return false;
			},
			//点击删除/取消
			delNewsClick(type){
				var tabBar=[]
				if(type==0){
					this.delnews=true
				}else if(type==1){
					this.delnews=false
				}
				for (let item of this.tabBars[this.tabCurrentIndex].newsList) {
					item.disabled=this.delnews
					item.checked=false
					tabBar.push(item)
				}
				this.tabBars[this.tabCurrentIndex].newsList=tabBar
			},
			//监听复选框
			checkboxGroupChange(e) {
				var s = e.join("|");
				this.delList=e
				console.log(this.delList)
			},
			//删除 音乐/新闻
			async delClick(id, type) {
				const res = await this.$myRequest({
					url: '/user/praise',
					method: 'post',
					header: {},
					data: {
						info_id: id,
						type: type
					}
				})
				this.$refs.uToast.show({
					title: this.$i18n.messages[this.$i18n.locale].pressrelease.delok,
					type: 'success'
				})
			},
			//试听音乐
			navToDetails(item, index, id) {
				for (let i = 0; i < this.tabBars.length; i++) {
					const tabLSIT = this.tabBars[i].newsList.map(items => {
						items.show = false
						return items
					})
				}
				this.innerAudioContext = uni.createInnerAudioContext();
				let srcs = 'https://music-asean.oss-cn-hongkong.aliyuncs.com' + item.music_file;
				this.tabBars[id].newsList[index].show = true;
				this.innerAudioContext = uni.createInnerAudioContext();
				this.innerAudioContext.autoplay = true;
				this.innerAudioContext.src = srcs
				this.innerAudioContext.onPlay(() => {
					console.log('开始播放');
				});
				this.innerAudioContext.onError((res) => {
					console.log(res);
					console.log(res.errCode);
				});
			},
			//跳转详情页面
			navTonews(news_id) {
				uni.navigateTo({
					url: `/pages/details/details?news_id=${news_id}`
				})
			},
			//关注
			async followClock(item) {
				const res = await this.$myRequest({
					url: '/user/follow',
					method: 'post',
					header: {},
					data: {
						up_uid: item.user_id
					}
				})
				let operation = ''
				res.data.operation == 1 ? operation = this.$i18n.messages[this.$i18n.locale].pressrelease.Focusok : operation = this.$i18n.messages[this.$i18n.locale].pressrelease.CancelFocus
				this.$refs.uToast.show({
					title: operation,
					type: 'success'
				})
				item.falis = !item.falis
			},
			//设置分类 
			async loadTabbars() {
				let tabList=[]
				if(getLanguage()==2){
					tabList = [{
						channelId: 1,
						channelName: this.$i18n.messages[this.$i18n.locale].recordlist.MusicStore
					}, {
						channelId: 2,
						channelName: this.$i18n.messages[this.$i18n.locale].recordlist.NewsStore
					}, {
						channelId: 3,
						channelName: this.$i18n.messages[this.$i18n.locale].recordlist.historyList
					}, {
						channelId: 4,
						channelName: this.$i18n.messages[this.$i18n.locale].recordlist.followList
					}]
				}else{
					tabList = [{
						channelId: 1,
						channelName: '音乐收藏'
					}, {
						channelId: 2,
						channelName: '新闻收藏'
					}, {
						channelId: 3,
						channelName: '历史记录'
					}, {
						channelId: 4,
						channelName: '关注列表'
					}]
				}
				tabList.forEach(item => {
					item.newsList = [];
					item.page_index = 1;
					item.loadMoreStatus = 0; //加载更多 0加载前，1加载中，2没有更多了
					item.refreshing = 0; //动画
				})
				this.tabBars = tabList;
				this.loadNewsList('add');
			},
			//列表
			async loadNewsList(type) {
				let tabItem = this.tabBars[this.tabCurrentIndex];
				let channel_id = tabItem.channelId //频道id
				let page_size = 10 //每页显示多少条数据
				if (type === 'refresh') {
					tabItem.newsList = []; //刷新前清空数组
					this.tabBars[this.tabCurrentIndex].page_index = 1
				}
				let page_index = tabItem.page_index //当前第几页
				var list_URL = ''
				if (this.tabCurrentIndex == 3) { //关注
					list_URL = '/user/get-follow-list/' + page_size + '/' + page_index
				} else if (this.tabCurrentIndex == 2) { //历史记录
					list_URL = '/user/history/' + page_size + '/' + page_index
				} else if (this.tabCurrentIndex == 1) { //新闻收藏
					list_URL = '/user/get-favorite/' + page_size + '/' + page_index
				} else if (this.tabCurrentIndex == 0) { //音乐收藏
					list_URL = '/user/get-favorite-music-list?pageIndex=' + page_size + '&pageSize=' + page_index
				}
				const res = await this.$myRequest({
					url: list_URL,
					header: {}
				})
				//type add 加载更多 refresh下拉刷新
				if (type === 'add') {
					if (tabItem.loadMoreStatus === 2) {
						return;
					}
					tabItem.loadMoreStatus = 1;
				}
				// #ifdef APP-PLUS
				else if (type === 'refresh') {
					tabItem.refreshing = true;
				}
				// #endif
				//setTimeout模拟异步请求数据
				setTimeout(() => {
					let list = res.data;
					if (list.length >= 1) {
						list.forEach(item => {
							if (item.duration) {
								item.show = false
								item.duration = this.s_to_hs(item.duration)
							}
							if (this.tabCurrentIndex == 3) {
								item.falis = true
							} else {
								item.checked = false
								item.disabled = false
							}
							tabItem.newsList.push(item);
						})
					}
					//下拉刷新 关闭刷新动画
					if (type === 'refresh') {
						this.$refs.mixPulldownRefresh && this.$refs.mixPulldownRefresh.endPulldownRefresh();
						// #ifdef APP-PLUS
						tabItem.refreshing = false;
						// #endif
						tabItem.loadMoreStatus = 0;
					}
					//上滑加载 处理状态
					if (type === 'add') {
						tabItem.loadMoreStatus = list.length == 0 ? 2 : 0;
					}
					this.tabBars[this.tabCurrentIndex].page_index++
				}, 1000)
			},
			//计算时长
			s_to_hs(s) {
				//计算分钟
				//算法：将秒数除以60，然后下舍入，既得到分钟数
				var h;
				h = Math.floor(s / 60);
				//计算秒
				//算法：取得秒%60的余数，既得到秒数
				s = s % 60;
				//将变量转换为字符串
				h += '';
				s += '';
				//如果只有一位数，前面增加一个0
				h = (h.length == 1) ? '0' + h : h;
				s = (s.length == 1) ? '0' + s : s;
				return h + ':' + s;
			},
			//下拉刷新
			onPulldownReresh() {
				this.loadNewsList('refresh');
			},
			//上滑加载
			loadMore() {
				this.loadNewsList('add');
			},
			//设置scroll-view是否允许滚动，在小程序里下拉刷新时避免列表可以滑动
			setEnableScroll(enable) {
				if (this.enableScroll !== enable) {
					this.enableScroll = enable;
				}
			},

			//tab切换
			async changeTab(e) { 
				this.delNewsClick(1) 
				if (this.innerAudioContext){//切换频道暂停音乐
					for (let i = 0; i < this.tabBars.length; i++) {
						const tabLSIT = this.tabBars[i].newsList.map(items => {
							items.show = false
							return items
						})
					}
					this.innerAudioContext.destroy()
				} 
				if (scrollTimer) {
					//多次切换只执行最后一次
					clearTimeout(scrollTimer);
					scrollTimer = false;
				}
				let index = e;
				//e=number为点击切换，e=object为swiper滑动切换
				if (typeof e === 'object') {
					index = e.detail.current
				}
				if (typeof tabBar !== 'object') {
					tabBar = await this.getElSize("nav-bar")
				}
				//计算宽度相关
				let tabBarScrollLeft = tabBar.scrollLeft;
				let width = 0;
				let nowWidth = 0;
				//获取可滑动总宽度
				for (let i = 0; i <= index; i++) {
					let result = await this.getElSize('tab' + i);
					width += result.width;
					if (i === index) {
						nowWidth = result.width;
					}
				}
				if (typeof e === 'number') {
					//点击切换时先切换再滚动tabbar，避免同时切换视觉错位
					this.tabCurrentIndex = index;
				}
				//延迟10ms,等待swiper动画结束再修改tabbar
				scrollTimer = setTimeout(() => {
					if (width - nowWidth / 2 > windowWidth / 2) {
						//如果当前项越过中心点，将其放在屏幕中心
						this.scrollLeft = width - nowWidth / 2 - windowWidth / 2;
					} else {
						this.scrollLeft = 0;
					}
					if (typeof e === 'object') {
						this.tabCurrentIndex = index;
					}
					this.tabCurrentIndex = index;
					//第一次切换tab，动画结束后需要加载数据
					let tabItem = this.tabBars[this.tabCurrentIndex];
					//if (this.tabCurrentIndex !== 0 && tabItem.loaded !== true) {
					if (tabItem.loaded !== true) {
						this.loadNewsList('add');
						tabItem.loaded = true;
					}
				}, 10)

			},
			//获得元素的size
			getElSize(id) {
				return new Promise((res, rej) => {
					let el = uni.createSelectorQuery().select('#' + id);
					el.fields({
						size: true,
						scrollOffset: true,
						rect: true
					}, (data) => {
						res(data);
					}).exec();
				});
			},
		}
	}
</script>

<style lang='scss' scoped>
	page,
	.content {
		background-color: #e8e8e8;
		height: 100%;
		overflow: hidden;
	}

	.main {
		background-color: #f0f0f0;
	}

	.channelTag {
		padding: 15rpx;
		display: inline-block;

		.tag-info {
			display: inline-block;
			float: left;
			margin: 15rpx 0 15rpx 30rpx;
		}
	}

	/* 顶部tabbar */
	.tab-frame {
		position: relative;

		.nab-icon {
			background-image: linear-gradient(90deg, rgba(255, 255, 255, 0.7), #ffffff);
			width: 13%;
			height: 90rpx;
			position: absolute;
			right: 0rpx;
			top: 0rpx;
			z-index: 10;

			.icon {
				margin: 17rpx;
				margin-right: 0rpx;
			}
		}
	}

	.nav-bar {
		position: relative;
		z-index: 10;
		height: 90upx;
		white-space: nowrap;
		width: 100%;
		box-shadow: 0 2upx 8upx rgba(0, 0, 0, .06);
		background-color: #fff;

		.nav-item {
			display: inline-block;
			width: 25%;
			height: 90upx;
			padding: 0 20rpx;
			text-align: center;
			line-height: 90upx;
			font-size: 30upx;
			color: #303133;
			position: relative;

			&:after {
				content: '';
				width: 0;
				height: 0;
				border-bottom: 4upx solid #ed4141;
				position: absolute;
				left: 50%;
				bottom: 0;
				transform: translateX(-50%);
				transition: .3s;
			}
		}

		.current {
			color: #ed4141;

			&:after {
				width: 50%;
			}
		}
	}

	.swiper-box {
		height: 100%;
	}

	.panel-scroll-box {
		height: 100%;

		.panel-item {
			background: #fff;
			padding: 30px 0;
			border-bottom: 2px solid #000;
		}
	}

	/* 音乐收藏 */
	.music-concen {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 150rpx;
		width: 750rpx;
		background-color: #fff;
		border-bottom: 1rpx solid #d4d4d4;

		.music-img {
			flex: 2;
			width: 130rpx;
			height: 130rpx;
			padding: 0 10rpx;

			image {
				width: 130rpx;
				height: 130rpx;
				border-radius: 50px;
			}
		}

		.music-text {
			flex: 6;

			view {
				font-size: 25rpx;
				color: #b1b1b1;
			}

			.txt {
				margin-bottom: 10rpx;
				font-size: 35rpx;
				color: #1e1e1e;
				font-weight: 600;
			}
		}

		.music-button {
			flex: 2;
			text-align: right;
			padding-right: 30rpx;

			button {
				color: #fff;
				background-color: #ed4141;
			}

			text {
				color: #ababab;
			}
		}
	}

	.img01 {
		display: block;
		animation: rotate 6s linear infinite;
	}

	@keyframes rotate {
		0% {
			transform: rotateZ(0deg);
			/*从0度开始*/
		}

		100% {
			transform: rotateZ(360deg);
			/*360度结束*/
		}
	}

	/* 批量删除 */
	.batchDel {
		position: fixed;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 750rpx;
		height: 100rpx;
		border-top: 1rpx solid #e3e9f0;
		font-size: 35rpx;
		color: #ff0000;
		background-color: #ffffff;
		bottom: 0;
	}

	/* 访谈 */
	.interview {
		.interview-content {
			border-bottom: 1rpx solid #d6d6d6;
			background-color: #fff;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 10rpx 30rpx;

			.content-info {
				display: flex;
				font-size: 26rpx;
				color: #909399;
				align-items: center; //子元素垂直居中

				.frame_img {
					width: 100rpx;
					height: 100rpx;
					border-radius: 50px;

					image {
						border-radius: 50px;
						width: 100rpx;
						height: 100rpx;
					}
				}

				text {
					margin-left: 20rpx;
					font-size: 30rpx;
					color: #000000;
				}
			}
		}
	}

	/* 新闻收藏 */
	.rec-section {
		background-color: #fff;
		margin-bottom: 10rpx;

		.introduce {
			padding: 15rpx;
			margin-right: 20rpx;
			display: flex;
			font-size: 26rpx;
			color: #909399;
			justify-content: center; //子元素水平居中
			align-items: center; //子元素垂直居中

			.introduce_img {
				width: 100rpx;
				height: 100rpx;
				border-radius: 50px;

				image {
					border-radius: 50px;
					width: 100%;
					height: 100%;
				}
			}

			.introduce_tltle {
				text {
					margin-right: 16rpx;
				}

				margin-left: 30rpx;
				flex: 4;

				view {
					font-weight: 500;
					font-size: 32rpx;
					color: #000000;
				}
			}
		}

		.rec-item {
			display: flex;
			padding: 20rpx 30rpx;
			position: relative;

			&:after {
				content: '';
				position: absolute;
				left: 30rpx;
				right: 0;
				bottom: 0;
				height: 0;
				border-bottom: 1px solid #eee;
				transform: scaleY(50%);
			}
		}

		.left {
			height: 140rpx;
			flex: 1;
			padding-right: 10rpx;
			overflow: hidden;
			padding-bottom: 52rpx;

			.title {
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 2;
				overflow: hidden;
				font-size: 32rpx;
				color: #303133;
				line-height: 44rpx;
			}

			.bot {
				padding-top: 10rpx;
				font-size: 26rpx;
				color: #909399;
				display: flex;
				width: 460rpx;
				line-height: 40rpx;
				padding-right: 30rpx;
				align-items: center;

				.del {
					font-size: 35rpx;
					margin-left: auto;
				}
			}

			.time {
				margin-left: 20rpx;
			}
		}

		.right {
			width: 220rpx;
			height: 140rpx;
			flex-shrink: 0;
			position: relative;

			.img {
				width: 100%;
				height: 100%;
			}

		}
	}
</style>
